export default class InputHandler {
  constructor(game) {
    this.game = game;
    this.touchStartX = null;
    this.touchStartY = null;
    this.isTouching = false;
    
    // 添加键盘状态
    this.keys = {
      left: false,
      right: false,
      up: false,
      down: false,
      attackA: false,
      attackB: false
    };
    
    // 标记是否已设置自定义回调
    this.hasCustomClickHandler = false;
    this.clickCallback = null;
    
    // 初始化事件
    try {
      console.log('Inicializando eventos de entrada...');
      this.initTouchEvents();
      this.initKeyboardEvents();
      console.log('Eventos de entrada inicializados correctamente');
    } catch (error) {
      console.error('Error al inicializar eventos de entrada:', error);
    }
  }
  
  initTouchEvents() {
    console.log('Configurando eventos táctiles...');
    
    // 清除可能的现有事件处理程序
    try {
      wx.offTouchStart();
      wx.offTouchMove();
      wx.offTouchEnd();
      console.log('Eventos táctiles anteriores eliminados');
    } catch (e) {
      console.warn('No se pudieron eliminar eventos táctiles anteriores:', e);
    }
    
    // 触摸开始
    wx.onTouchStart((event) => {
      if (!event || !event.touches || event.touches.length === 0) {
        console.warn('Evento táctil sin datos válidos');
        return;
      }
      
      const touch = event.touches[0];
      if (!touch) {
        console.warn('Primer toque no válido');
        return;
      }
      
      try {
        const { x, y } = this.convertTouchPosition(touch);
        
        // 记录触摸起始位置
        this.touchStartX = x;
        this.touchStartY = y;
        this.isTouching = true;
        
        // 先尝试使用游戏状态相关的触摸处理
        if (this.handleGameStateTouch(x, y)) {
          // 如果游戏状态处理已经处理了触摸，则不再触发自定义回调
          return;
        }
        
        // 如果有自定义回调且没有被游戏状态处理消费，则执行自定义回调
        if (this.hasCustomClickHandler && typeof this.clickCallback === 'function') {
          this.clickCallback(x, y);
        }
      } catch (error) {
        console.error('Error al procesar toque:', error);
      }
    });
    
    // 触摸移动
    wx.onTouchMove((event) => {
      if (!this.isTouching || this.game.state !== 'running' || !event.touches[0]) return;
      
      try {
        const touch = event.touches[0];
        const { x } = this.convertTouchPosition(touch);
        
        // 计算水平移动方向
        const moveX = x - this.touchStartX;
        if (Math.abs(moveX) > 10) { // 添加一个小的阈值，避免微小移动
          if (this.game.player && typeof this.game.player.move === 'function') {
            this.game.player.move(moveX > 0 ? 1 : -1);
          }
        }
        
        // 更新起始位置
        this.touchStartX = x;
      } catch (error) {
        console.error('Error al procesar movimiento táctil:', error);
      }
    });
    
    // 触摸结束
    wx.onTouchEnd(() => {
      this.isTouching = false;
      if (this.game.state === 'running' && this.game.player) {
        if (typeof this.game.player.stopMove === 'function') {
          this.game.player.stopMove();
        }
      }
    });
    
    console.log('Eventos táctiles configurados correctamente');
  }
  
  initKeyboardEvents() {
    // 监听键盘按下事件
    wx.onKeyDown((event) => {
      switch(event.key) {
        case 'ArrowLeft':
          this.keys.left = true;
          break;
        case 'ArrowRight':
          this.keys.right = true;
          break;
        case 'ArrowUp':
          this.keys.up = true;
          break;
        case 'ArrowDown':
          this.keys.down = true;
          break;
        case 'a':
        case 'A':
          this.keys.attackA = true;
          break;
        case 'b':
        case 'B':
          this.keys.attackB = true;
          break;
      }
    });
    
    // 监听键盘释放事件
    wx.onKeyUp((event) => {
      switch(event.key) {
        case 'ArrowLeft':
          this.keys.left = false;
          break;
        case 'ArrowRight':
          this.keys.right = false;
          break;
        case 'ArrowUp':
          this.keys.up = false;
          break;
        case 'ArrowDown':
          this.keys.down = false;
          break;
        case 'a':
        case 'A':
          this.keys.attackA = false;
          break;
        case 'b':
        case 'B':
          this.keys.attackB = false;
          break;
      }
    });
  }
  
  // 转换触摸坐标
  convertTouchPosition(touch) {
    const system = wx.getSystemInfoSync();
    let x = touch.clientX;
    let y = touch.clientY;
    
    // 如果是竖屏设备，交换坐标
    if (system.windowWidth < system.windowHeight) {
      [x, y] = [y, system.windowWidth - x];
    }
    
    // 转换为游戏坐标
    return {
      x: this.game.getActualX(x),
      y: this.game.getActualY(y)
    };
  }
  
  // 添加按钮点击检测方法
  checkButtonClick(touchX, touchY, buttonX, buttonY, buttonWidth, buttonHeight) {
    return (
      touchX >= buttonX - buttonWidth/2 &&
      touchX <= buttonX + buttonWidth/2 &&
      touchY >= buttonY - buttonHeight/2 &&
      touchY <= buttonY + buttonHeight/2
    );
  }
  
  // 添加获取键盘状态的方法
  getKeyState() {
    return this.keys;
  }
  
  // 添加通用点击回调
  setClickCallback(callback) {
    // 避免重复设置相同的回调函数
    if (this.hasCustomClickHandler && this.clickCallback === callback) {
      return; // 如果已经设置了相同的回调，直接返回
    }
    
    console.log('Configurando callback de clic personalizado');
    this.clickCallback = callback;
    this.hasCustomClickHandler = true;
  }
  
  // 清除点击回调
  clearClickCallback() {
    if (!this.hasCustomClickHandler) {
      return; // 如果没有设置回调，不需要清除
    }
    
    console.log('Eliminando callback de clic personalizado');
    this.clickCallback = null;
    this.hasCustomClickHandler = false;
  }
  
  // 处理游戏不同状态下的点击
  handleGameStateTouch(x, y) {
    // 如果有自定义回调且游戏处于暂停状态，优先处理暂停菜单
    if (this.game.state === 'paused') {
      // 继续游戏按钮
      if (this.checkButtonClick(x, y, 
          this.game.canvas.width / 2, this.game.canvas.height / 2, 
          200, 50)) {
        console.log('恢复游戏按钮被点击');
        if (typeof this.game.setState === 'function') {
          this.game.setState('running');
        } else {
          this.game.state = 'running';
        }
        return true;
      }
      
      // 返回主菜单按钮
      if (this.checkButtonClick(x, y,
          this.game.canvas.width / 2, this.game.canvas.height / 2 + 70,
          200, 50)) {
        console.log('返回主菜单按钮被点击');
        this.game.reset();
        return true;
      }
      return false; // 点击在暂停菜单上但没有点击按钮
    }
    
    // 游戏结束或胜利状态下，点击重新开始
    if (this.game.state === 'gameOver' || this.game.state === 'victory') {
      console.log('游戏结束状态下点击，重新开始');
      this.game.reset();
      return true;
    }
    
    // 游戏运行中的操作
    if (this.game.state === 'running') {
      // 检查是否点击了暂停按钮
      if (x > this.game.canvas.width - 50 && x < this.game.canvas.width - 10 &&
          y > 10 && y < 50) {
        console.log('暂停按钮被点击');
        if (typeof this.game.setState === 'function') {
          this.game.setState('paused');
        } else {
          this.game.state = 'paused';
        }
        return true;
      }
      
      // 跳跃 - 只有当点击不是在UI元素上时才触发跳跃
      if (this.game.player && typeof this.game.player.jump === 'function') {
        console.log('触发玩家跳跃');
        this.game.player.jump();
        return true;
      }
    }
    
    return false; // 未处理的点击
  }
  
  // 处理默认触摸 - 现在已集成到handleGameStateTouch中，保留此方法是为了兼容性
  handleDefaultTouch(x, y, event) {
    this.touchStartX = x;
    this.touchStartY = y;
    this.isTouching = true;
    
    this.handleGameStateTouch(x, y);
  }
} 